app.controller('roleViewController', ['$scope', 'httpWrapService', 'dialogs', '$state', '$stateParams',
                        '$location', '$anchorScroll', 'AlertFactory','GridFactory','validationService',
                function ($scope, httpWrapService, dialogs, $state, $stateParams, $location, $anchorScroll, AlertFactory,GridFactory,validationService) {
    $scope.entity = {};

    $scope.id = $stateParams.id;
    $scope.type = $stateParams.type || 'add';
    $scope.Alert = AlertFactory.newInstance();


    var columnDefs = [
        {name: "权限名", field: "name"},
        {name: "权限", field: "authority"} ,
        {name: "过期时间", field: "expiredDt", cellFilter : 'date : "yyyy-MM-dd"'} //,
    ];

    var loadSuccessCallbak = function(){
        if($scope.id) {
            httpWrapService.post('system/role/view/' + $scope.id + '.do').then(function (res) {
                $scope.entity = res.data.entity;
                $scope.type = 'update';

                // 初始化选择权限
                if(res.data.map.auths) {
                    var authids  = {};
                    for(var i = 0; i < res.data.map.auths.length; i++) {
                        var ra = res.data.map.auths[i];
                        authids[ra.authId] = ra;
                    }

                    // 选中行
                    $scope.Grid.selectRows(authids);
                }
            });
        }
    }
    $scope.Grid = GridFactory.newInstance({
        url : "system/authority/list.do",
        loadSuccessCallbak : loadSuccessCallbak,
        columnDefs : columnDefs,
        gridOptions : {
            multiSelect : true
        }
    });


    $scope.Grid.load();

    $scope.unique = function(value){
        return validationService.unique({
            entityName : "common.rbac.po.Role",
            field : "role",
            value : value,
            id : $scope.id
        })
    }

    $scope.save = function () {
        var rows =  $scope.Grid.getSelectedRows();
        var auths = [];
        if(rows) {
            for(var i = 0; i < rows.length; i++) {
                var obj = {
                    authId : rows[i].id,
                    roleId : $scope.id
                }
                auths.push(obj);
            }
        }
        httpWrapService.defaultSave( 'system/role/' + $scope.type + '.do',{
            entity : $scope.entity,
            auths : auths
        }, $scope).then(function (res) {
            $state.go('app.system.role.list');
        });

        // 保存成功返回列表页面

    }

    $scope.canle = function () {
        // 后退到列表页面
        $state.go('app.system.role.list');
    }


}]);
